﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using WqLunTan.DBContext;
using WqLunTan.Filters;
using WqLunTan.Models.DataBase;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace WqLunTan.Controllers
{
    /// <summary>
    /// 控制器基类
    /// </summary>
    public class BaseController : Controller
    {
        protected MySqlDbContext DbContext { get; set; }

        protected ILogger Logger { get; set; }

        /// <summary>
        /// 当前用户的ipv4地址
        /// </summary>
        protected string UserIPAddress { get; set; } = string.Empty;

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (DbContext == null)
            {
                DbContext = context.HttpContext.RequestServices.GetService<MySqlDbContext>();
            }
            if (Logger == null)
            {
                Logger = context.HttpContext.RequestServices.GetService<ILogger<BaseController>>();
            }
            if (string.IsNullOrWhiteSpace(UserIPAddress))
            {
                if (context.HttpContext.Request.Cookies.TryGetValue("ip", out var ip))
                {
                    if (!string.IsNullOrWhiteSpace(ip))
                    {
                        UserIPAddress = ip;
                    }
                }
            }
            base.OnActionExecuting(context);
        }

        /// <summary>
        /// 当前登录的用户, 有效期建议设置 5-30 分钟之间,
        /// 先验证jwt token, 再验证用户登录时间, 获取最新的用户权限等数据
        /// 如果用户为null, 则用户未登录
        /// </summary>
        public WqUser LoginUser { get; set; }

        /// <summary>
        /// 返回json字符串
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        /// <param name="StatuCode"></param>
        /// <returns></returns>
        protected JsonResult JsonMsg(string msg, object data, int StatuCode = 200)
        {
            return new JsonResult(new { msg, data }) { StatusCode = StatuCode };
        }

        /// <summary>
        /// 成功消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected JsonResult JsonOkResult(string data)
        {
            return new JsonResult(new { msg = "ok", data });
        }

        /// <summary>
        /// 失败消息
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        protected JsonResult JsonFailResult(string data)
        {
            return new JsonResult(new { msg = "fail", data });
        }
    }
}